package com.feri.rbacsys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.feri.rbacsys.dao.DepositoryDao;
import com.feri.rbacsys.dao.ExportOrderDao;
import com.feri.rbacsys.dao.ImportOrderDao;
import com.feri.rbacsys.entity.Depository;
import com.feri.rbacsys.entity.ExportOrder;
import com.feri.rbacsys.service.intf.ExportOrderService;
import com.feri.rbacsys.util.AuthUtil;
import com.feri.rbacsys.vo.R;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * (ExportOrder)表服务实现类
 *
 * @author makejava
 * @since 2023-03-28 10:02:51
 */
@Service("exportOrderService")
public class ExportOrderServiceImpl extends ServiceImpl<ExportOrderDao, ExportOrder> implements ExportOrderService {
    @Resource
    private ExportOrderDao dao;
    @Resource
    private DepositoryDao depositoryDao;
    @Override
    public R selectPage(Integer page, Integer size, String orderNum, String productName) {

        return R.ok(dao.all(new Page<>(page,size),orderNum,productName));
    }

    @Override
    public R exportProduct(ExportOrder exportOrder) {
        if(exportOrder.getType()==0){
            int count = depositoryDao.selectCount(exportOrder.getProductId());
            int need = exportOrder.getAmount();
            if(count >= need){
                LambdaQueryWrapper<Depository> lqw = new LambdaQueryWrapper<>();
                lqw.eq(Depository::getProductId,exportOrder.getProductId())
                        .orderByAsc(Depository::getDeadline)
                        .eq(Depository::getStatus,0);
                List<Depository> list = depositoryDao.selectList(lqw);

                exportOrder.setUserId(AuthUtil.getUid());
                exportOrder.setExportDate(new Date());
                dao.updateById(exportOrder);

                for(Depository depository : list){
                    if(depository.getAmount()<=need){
                        depository.setStatus(1);
                        need=need-depository.getAmount();
                        depository.setAmount(0);
                        depositoryDao.updateById(depository);

                    }else{
                        depository.setAmount(depository.getAmount()-need);
                        depositoryDao.updateById(depository);
                        return R.ok("出库成功");

                    }
                }

            }else {
                return R.fail("库存不足不能出库");
            }
        }

        return R.fail("不支持出库");
    }
}

